package jznet

import (
        "time"
        "sync"
        "net"
    )
    
type jzSocket struct {
    datachannel chan []byte
    msgPack *jzMsgPack
    bufferflag bool 
    locak *sync.Mutex
    conn net.Conn
}

func NewjzSocket(conn net.Conn) *jzSocket {
    return &jzSocket {
        datachannel : make(chan []byte,1024 * 24),
        msgPack : NewjzMsgPack(),
        bufferflag : false,
        lock : &sync.Mutex{},
        conn : conn,
    }
}

func (socket *jzSocket) Start() {
    go socket.handleChannelData()
    go socket.syncData()
}

func (socket* jzSocket) SendCmd(data []byte) {
    socket.datachannel <- data
}

func (socket *jzSocket) SetBuffer(buffer bool) {
    var flag []byte
    if buffer {
        flag = []byte("1")
    } else {
        flag = []byte("0")
    }
    socket.datachannel <- flag
}

func (socket* jzSocket) handleChannelData() {
    for true {
        data := <- socekt.datachannel
        if len(data) == 1 {
            if string(data) == "0" {
                socket.bufferflag = false
            } else if string(data) == "1" {
                socket.bufferflag = true
            }
        } else {
            if socket.bufferflag {
                socket.syncDirectData(data)
            } else {
                socket.lock.Lock()
                socket.msgPack.AddMsg(data)
                socket.lock.Unlock()
            }
        }
    }
}

func (socket *jzSocket) syncData () {
    for true {
        time.Sleep(10 * time.Millisecond)
        
        packlen := socket.msgPack.GetLen()
        if packlen > 0 {
            socket.lock.Lock()
            rawdata := socket.msgPack.GetMsg()
            socket.msgPack.Reset()
            socket.lock.Unlock()
            
            socket.conn.Write(rawdata)
            //sendlen,err := socket.conn.Write(rawdata)
            
        }
    }
}

func (socket *jzSocket) Final() {
    
}